<?php if (!defined("_ECRIRE_INC_VERSION")) return; if (class_exists('PdkListEditor')) return;
/**
 * SPIP Plugin Development Kit
 *
 * @author     Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 * @license    GNU/GPL
 * @package    plugins
 * @subpackage pdk
 * @category   outils
 * @copyright  (c) Aleksey Yaroshchuk 2011-2012
 * @link       http://www.spip-contrib.net/Developmet-Kit
 * @version    1.0.0
 */

include_spip('classes/pdk_model');
include_spip('inc/session');
/** 
 *  This class helps to work with lists (references)
 *
 *  @author Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 */
//TODO: Возможно стоит создать три отдельных функции для апдейта, инсерта и удаления
class PdkListEditor {
    /**
     *  Model whose fields will be edited
     */
    private $model;
    
    public function __construct($model) {        
        $this->model = $model;
    }
    
    /**
     *  Edit fields using given arrays
     *  $elements_update format: array([id_element1]=>array([field1]=>[value], [field2]=>[value], ...),
     *                                 [id_element2]=>array([field1]=>[value], [field2]=>[value], ...),
     *                                 ...
     *                                 )
     *  $elements_insert format: array([]=>array([field1]=>[value], [field2]=>[value], ...),
     *                                 []=>array([field1]=>[value], [field2]=>[value], ...),
     *                                 ...
     *                                 )
     *  $elements_delete format: array([id_element1]=>[id_element1], [id_element2]=>[id_element2], ...)
     */
    public function EditElements($elements_update = false, $elements_insert = false, $elements_delete = false) {        
        $flag_result = true;
        
        // Update elemetnts
        if ($elements_update) 
            foreach ($elements_update as $element_id=>$element) {
                // Use model to filter data
                $data = $this->model->form_data_from_array($element);
                if (!$this->model->update_by_id($element_id, $data))
                    $flag_result = false;
            }
        
        // Delete elements
        if ($elements_delete)
            foreach ($elements_delete as $element_id) {
                if (!$this->model->delete_by_id($element_id))
                    $flag_result = false;
            }
        
        
        // Insert elements
        if ($elements_insert)
            foreach ($elements_insert as $key=>$element) {
                // Use model to filter data
                $data = $this->model->form_data_from_array($element);
                if (!$this->model->insert($data))
                    $flag_result = false;
            }
            
        return $flag_result;
    }
}
?>